//
//  MP4VideoView.swift
//  CMB250716
//
//  Created by Assistant on 2024-07-28.
//

import Foundation
import SwiftUI
import AVFoundation
import UIKit

// MARK: - MP4视频播放器
struct MP4VideoView: UIViewRepresentable {
    let videoName: String
    
    func makeUIView(context: Context) -> UIView {
        let containerView = VideoContainerView()
        containerView.backgroundColor = UIColor.clear // 透明背景
        
        // 查找视频文件
        guard let videoURL = Bundle.main.url(forResource: videoName, withExtension: "mp4") else {
            // 视频文件未找到
            
            // 列出Bundle中的所有mp4文件
            if let bundleContents = try? FileManager.default.contentsOfDirectory(atPath: Bundle.main.bundlePath) {
                _ = bundleContents.filter { $0.hasSuffix(".mp4") }
                // Bundle中的MP4文件列表已检查
            }
            
            // 显示错误占位符
            let placeholderView = createErrorPlaceholderView()
            containerView.addSubview(placeholderView)
            placeholderView.translatesAutoresizingMaskIntoConstraints = false
            NSLayoutConstraint.activate([
                placeholderView.topAnchor.constraint(equalTo: containerView.topAnchor),
                placeholderView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor),
                placeholderView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor),
                placeholderView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor)
            ])
            return containerView
        }
        
        // 视频文件加载成功
        
        // 直接创建AVPlayer和AVPlayerLayer
        let player = AVPlayer(url: videoURL)
        let playerLayer = AVPlayerLayer(player: player)
        
        playerLayer.videoGravity = .resizeAspectFill
        playerLayer.backgroundColor = UIColor.clear.cgColor
        
        // 立即添加到容器
        containerView.layer.addSublayer(playerLayer)
        containerView.playerLayer = playerLayer
        
        // 监听播放状态
        player.addObserver(context.coordinator, forKeyPath: "status", options: [.new], context: nil)
        
        // 设置循环播放
        NotificationCenter.default.addObserver(
            forName: .AVPlayerItemDidPlayToEndTime,
            object: player.currentItem,
            queue: .main
        ) { _ in
            player.seek(to: CMTime.zero)
            player.play()
        }
        
        // 监听音频会话通知
        NotificationCenter.default.addObserver(
            forName: .videoShouldStop,
            object: nil,
            queue: .main
        ) { _ in
            player.pause()
        }
        
        NotificationCenter.default.addObserver(
            forName: .videoShouldResume,
            object: nil,
            queue: .main
        ) { _ in
            player.play()
        }
        
        // 预加载并自动播放
        player.automaticallyWaitsToMinimizeStalling = false
        DispatchQueue.main.async {
            player.play()
        }
        
        // 存储player引用以避免被释放
        objc_setAssociatedObject(containerView, &AssociatedKeys.player, player, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        objc_setAssociatedObject(containerView, &AssociatedKeys.playerLayer, playerLayer, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        
        return containerView
    }
    
    func updateUIView(_ uiView: UIView, context: Context) {
        // 更新playerLayer的frame
        if let playerLayer = objc_getAssociatedObject(uiView, &AssociatedKeys.playerLayer) as? AVPlayerLayer {
            playerLayer.frame = uiView.bounds
        }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
    
    class Coordinator: NSObject {
        override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
            if keyPath == "status", let player = object as? AVPlayer {
                switch player.status {
                case .readyToPlay:
                    // 视频准备就绪
                    break
                case .failed:
                    // 视频播放失败
                    break
                case .unknown:
                    // 视频状态未知
                    break
                @unknown default:
                    // 未知的播放状态
                    break
                }
            }
        }
    }
    
    private func createErrorPlaceholderView() -> UIView {
        let placeholderView = UIView()
        placeholderView.backgroundColor = UIColor.systemOrange
        placeholderView.layer.cornerRadius = 15
        placeholderView.layer.borderWidth = 2
        placeholderView.layer.borderColor = UIColor.systemRed.cgColor
        
        let stackView = UIStackView()
        stackView.axis = .vertical
        stackView.alignment = .center
        stackView.spacing = 12
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        let iconImageView = UIImageView(image: UIImage(systemName: "exclamationmark.triangle.fill"))
        iconImageView.tintColor = UIColor.systemRed
        iconImageView.contentMode = .scaleAspectFit
        
        let titleLabel = UILabel()
        titleLabel.text = "视频文件未找到"
        titleLabel.textColor = UIColor.systemRed
        titleLabel.font = UIFont.boldSystemFont(ofSize: 16)
        titleLabel.textAlignment = .center
        
        let detailLabel = UILabel()
        detailLabel.text = "\(videoName).mp4"
        detailLabel.textColor = UIColor.darkGray
        detailLabel.font = UIFont.systemFont(ofSize: 12)
        detailLabel.textAlignment = .center
        
        stackView.addArrangedSubview(iconImageView)
        stackView.addArrangedSubview(titleLabel)
        stackView.addArrangedSubview(detailLabel)
        
        placeholderView.addSubview(stackView)
        
        NSLayoutConstraint.activate([
            stackView.centerXAnchor.constraint(equalTo: placeholderView.centerXAnchor),
            stackView.centerYAnchor.constraint(equalTo: placeholderView.centerYAnchor),
            iconImageView.widthAnchor.constraint(equalToConstant: 50),
            iconImageView.heightAnchor.constraint(equalToConstant: 50)
        ])
        
        return placeholderView
    }
}

// MARK: - Video Container View
class VideoContainerView: UIView {
    var playerLayer: AVPlayerLayer?
    
    override func layoutSubviews() {
        super.layoutSubviews()
        if let playerLayer = playerLayer {
            playerLayer.frame = bounds
        }
    }
}

// MARK: - Associated Keys for MP4VideoView
private struct AssociatedKeys {
    static var player: UInt8 = 0
    static var playerLayer: UInt8 = 0
}